/*
 * 同城信息发布
 * author: huangbin
 * 技术支持微信号：wxid_i8yk4fp0uep322
 * 开源协议：MIT
 *  *Copyright (c) 2018 https://www.tczhb.club All rights reserved.
 */
var Api = require('../../utils/api.js');
var wxRequest = require('../../utils/wxRequest.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var app = getApp();
var imgcnt = app.globalData.post_img_num;
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone_isopen: true,
    gpsaddress: "位置",
    category_id: 0, //分类id 
    category_name: "", //分类名称
    phone_isopen: true, //是否填写手机号码
    imglist: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //传值过来的分类id
    var category_id = options.id;
    var navTitle = options.name + "-发布";
    wx.setNavigationBarTitle({
      title: navTitle
    });
    that.setData({
      category_id: category_id,
      category_name: options.name
    });
    //QQ地图插件初始化
    qqmapsdk = new QQMapWX({ key: 'XPPBZ-GGS3F-2HBJG-NZANQ-R567V-F4BTE' });
    that.gpsloc();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  /**
   * 打开地图选择位置
   */
  open_map_chonse: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
          gpsaddress: res.address
        });
        //address: res.name || res.address
      },
      fail: function (res) {
        // wx.showToast({
        //   image: '../../resource/images/static/error.png',
        //   title: '调用失败,本机不支持地图选择地址!',
        // });
      },
      complete: function (res) {
        //console.log(res);
      }
    });
  },
  /**
   * 获取位置
   */
  gpsloc: function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (mapsucres) {
        wx.setStorageSync('latitude', mapsucres.latitude);
        wx.setStorageSync('longitude', mapsucres.longitude);
        that.setData({
          longitude: mapsucres.longitude,
          latitude: mapsucres.latitude
        });
        that.getLocinfo_revLf(mapsucres.latitude, mapsucres.longitude);
        // var speed = res.speed
        // var accuracy = res.accuracy
      },
      fail: function () {
        wx.showModal({
          title: '警告',
          content: '发布消息必须要地理位置信息',
          confirmText: '去设置',
          success: function (res) {
            if (res.confirm) {

              wx.openSetting({
                success: function (pdata) {
                  if (pdata) {
                    if (pdata.authSetting["scope.userLocation"] == true) {
                      console.log('取得授权信息成功');
                      that.getLocinfo();
                    } else {
                      console.log('===========')
                      that.gpsloc();
                    }
                  }
                }
              });
              console.log('用户点击确定')
            } else if (res.cancel) {
              that.gpsloc();
              // console.log('用户点击取消')
            }
          }
        });
      }
    });
  },
  /**
   * 直接内解析
   */
  getLocinfo_revLf: function (latitude, longitude) {
    var that = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      coord_type: 5,
      success: function (res) {
        console.log('地址逆解析:')
        console.log(res);
        console.log(res.result.ad_info);
        that.setData({
          'nation_code': res.result.ad_info.nation_code,
          'nation': res.result.ad_info.nation,
          'province': res.result.ad_info.province,
          'city_code': res.result.ad_info.city_code,
          'city': res.result.ad_info.city,
          'district': res.result.ad_info.district
        });
        that.setData({
          gpsaddress: res.result.address
        });
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  /**
   * 地址解析 先获取 
   */
  getLocinfo: function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude
        });
        wx.setStorageSync('latitude', res.latitude);
        wx.setStorageSync('longitude', res.longitude);
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          coord_type: 5,
          success: function (res) {
            console.log('地址逆解析:')
            console.log(res);
            console.log(res.result.ad_info);
            that.setData({
              'nation_code': res.result.ad_info.nation_code,
              'nation': res.result.ad_info.nation,
              'province': res.result.ad_info.province,
              'city_code': res.result.ad_info.city_code,
              'city': res.result.ad_info.city,
              'district': res.result.ad_info.district
            });
            that.setData({
              gpsaddress: res.result.address
            });
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            // console.log(res);
          }
        });
      }
    });
  },
  /**
   * 选择图片
   */
  choosePic: function () {
    var that = this;
    var imglist = this.data.imglist;
    var imglistlength = imglist.length;
    //imgcnt
    wx.chooseImage({
      count: imgcnt - imglistlength, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有 'original', 
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        // console.log(tempFilePaths)
        for (var i = 0, len = tempFilePaths.length; i < len; i++) {
          imglist.push(tempFilePaths[i]);
        }
        that.setData({
          imglist: imglist,
          upimgbtt: imglist.length >= imgcnt
        });
      },
      fail: function (res) {
        // wx.showModal({
        //   title: '图片选择错误!',
        //   content: JSON.stringify(res),
        // })
      }
    });
  },
  /**
   * 图片删除
   */
  pic_remove: function (e) {
    Array.prototype.indexOf = function (val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) return i } return -1 };
    Array.prototype.remove = function (val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1) } };
    var that = this;
    var imglist = this.data.imglist;
    wx.showModal({
      title: '提示',
      content: '是否删除图片?',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          imglist.remove(e.currentTarget.dataset.img);
          that.setData({
            imglist: imglist,
            upimgbtt: imglist.length >= imgcnt
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //发布
  formSubmit: function(e){
    var that = this;
    var formobj = e.detail.value;
    //发布内容
    var p_content = formobj.post_content;
    //发布地址
    var p_address = formobj.gpsaddress;
    //构造文章标题
    var p_title = app.globalData.userInfo.nickName + "-" + that.data.category_name + "-信息发布";
    //地理纬度
    var p_latitude = that.data.latitude;
    //地理经度
    var p_longitude = that.data.longitude;
    //手机号码
    var p_phone = formobj.phone;
    if (p_content == '' && !p_content) {
      wx.showModal({
        title: '提示',
        content: '消息内容不能为空!',
        showCancel: false
      })
      return;
    }
    if (p_phone == '' && !p_phone){
      wx.showModal({
        title: '提示',
        content: '手机号码不能为空!',
        showCancel: false
      })
      return;      
    }
    if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(p_phone))) {
      wx.showModal({
        title: '提示',
        content: '手机号码格式不正确!',
        showCancel: false
      })
      return;       
    }
    var p_gop_objcet = {
      latitude: p_latitude,
      longitude: p_longitude,
      cellphone: p_phone,
      address: p_address
    }
    var p_gop_str = JSON.stringify(p_gop_objcet);
    //分类id
    var p_cat_id = that.data.category_id;
    /*发布信息*/
    var createUrl = Api.creatPost();   //接口url
     //上传的信息
    var data = {
      post_content: p_content,
      more: p_gop_str,
      post_title: p_title,
      categories: [p_cat_id]
    }
    wx.showLoading({
      title: '信息发布中...',
      mask: true
    });                
    /* 上传图片 */
    var filePaths = that.data.imglist
    var length = filePaths.length; //总共个数
    if (length > 0) {
      var successUp = 0; //成功个数
      var failUp = 0; //失败个数
      var i = 0; //第几个
      var photosUrlArr = [];
      var photosNameArr = [];
      that.uploadImage(filePaths, successUp, failUp, i, length, data, photosNameArr, photosUrlArr);
    }
    else
    {
      that.uploadInfo(data);
    }
  },
  //上传信息
  uploadInfo:function(data){
    var that = this;
    var createUrl = Api.creatPost();   //接口url
    var postCreateRequest = wxRequest.postRequest(createUrl, data);
    postCreateRequest.then(res => {
      if (res.statusCode == 200) {
        console.log('创建成功');
        wx.hideLoading();
        that.redictMyPublic();
      }
    })
  },
  //上传图片
  uploadImage: function (filePaths, successUp, failUp, i, length, info_data, photosNameArr, photosUrlArr){
    var that = this;
    var uploadUrl = Api.uploadPic();
    var token = wx.getStorageSync('token');
    var photoObj = {};
    wx.uploadFile({
      url: uploadUrl,
      filePath: filePaths[i],
      name: 'file',
      formData: {
        'app': 'portal'
      },
      header: {
        'XX-Token': token,
        "Content-Type": "multipart/form-data",
        'XX-Device-Type': 'wxapp'
      },
      success: (resp) => {
        console.log('suc->图片上传')
        console.log(resp)
        if(resp.statusCode == 200){
          var res = JSON.parse(resp.data);
          if(res.code == 200){
            photosNameArr.push(res.data.name);
            photosUrlArr.push(res.data.filepath);
          }
          successUp++;
        }
      },
      fail: (res) => {
        failUp++;
      },
      complete: () => {
        i++;
        if (i == length) {
          photoObj.photos_names = photosNameArr;
          photoObj.photos_urls = photosUrlArr;
          var infoDataMoreObj = JSON.parse(info_data.more);
          infoDataMoreObj.photos = photoObj;
          info_data.more = JSON.stringify(infoDataMoreObj);
          that.uploadInfo(info_data);
          console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败！');
        }
        else {  //递归调用uploadDIY函数
          that.uploadImage(filePaths, successUp, failUp, i, length, info_data, photosNameArr, photosUrlArr);
        }
      },
    });
  },
  //跳转到我发布的
  redictMyPublic: function (e) {
    var url = '../list/list?list_type=myPublish';
    wx.redirectTo({
      url: url
    });
  },
  //跳转到发布声明
  powerDrawer: function (e){
    var url = '../publish/myPublish';
    wx.navigateTo({
      url: url
    });
  }
})